package carson.web.mvc;

import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 该类用于将 JSON 格式的内容发送到响应
 *
 * @author Carson Chen
 */
public class JsonResult extends AbstractResult {

    /**
     * 实例化JsonResult
     *
     * @param data 要序列化的数据
     */
    public JsonResult(Object data) {
        this(data, "application/json");
    }

    /**
     * 实例化JsonResult
     *
     * @param data        要序列化的数据
     * @param contentType 内容类型
     */
    public JsonResult(Object data, String contentType) {
        this(data, contentType, "utf-8");
    }

    /**
     * 实例化JsonResult
     *
     * @param data            要序列化的数据
     * @param contentType     内容类型
     * @param contentEncoding 内容编码
     */
    public JsonResult(Object data, String contentType, String contentEncoding) {
        this.data = data;
        this.contentType = contentType;
        this.contentEncoding = contentEncoding;
    }

    private String contentEncoding;

    private String contentType;

    private Object data;

    /**
     * 获取内容编码
     *
     * @return 内容编码
     */
    public String getContentEncoding() {
        return contentEncoding;
    }

    /**
     * 设置内容编码
     *
     * @param contentEncoding 内容编码
     */
    public void setContentEncoding(String contentEncoding) {
        this.contentEncoding = contentEncoding;
    }

    /**
     * 获取内容类型
     *
     * @return 内容类型
     */
    public String getContentType() {
        return contentType;
    }

    /**
     * 设置内容类型
     *
     * @param contentType 内容类型
     */
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    /**
     * 获取要序列化的数据
     *
     * @return 要序列化的数据
     */
    public Object getData() {
        return data;
    }

    /**
     * 设置要序列化的数据
     *
     * @param data 要序列化的数据
     */
    public void setData(Object data) {
        this.data = data;
    }

    @Override
    public void executeResult(HttpServletRequest request, HttpServletResponse response) {
        String json = JSON.toJSONString(this.data);
        try {
            response.setCharacterEncoding(this.contentEncoding);
            response.setContentType(this.contentType);
            PrintWriter pw = response.getWriter();
            pw.print(json);
            pw.flush();
        } catch (IOException e) {

        }
    }
}
